package com.rockymew.business.service;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.rockymew.core.utility.http.HMACSHA1;
import com.rockymew.core.utility.http.HttpConnectionException;
import com.rockymew.core.utility.http.HttpTool;

import freemarker.log.Logger;

public class PoloniexApi {
	 final String API_KEY = "V5B7M2H0-Y48KQ784-385Q0O3C-LV8AXOOI";
	 final String API_SECRET= "d6d00956abf40ccbf7f23df7c05ddfb7d3420106ed715777b77b0f3d581f8ddfd9162dff2b8c1423452a9e1c728acde98b79ace1a11d2c33894b512d4e7b22cd";
	 final String TRADING_URL = "https://poloniex.com/tradingApi";
	 final String PUBLIC_URL = "https://poloniex.com/public";
	 HttpTool httpTool = new HttpTool();
	 
	 private String  api_query(String command, Map req) {
		 String ret="";
		 if(command.equals("returnTicker") || command.equals("return24Volume")){
	           try {
				ret =  HttpTool.get("https://poloniex.com/public?command=" + command);
			} catch (HttpConnectionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	            //return json.loads(ret.read())
		 }
		 else if(command.equals("returnOrderBook")){
	            try {
	            	String currencyPair= (String) req.get("currencyPair");
					ret = HttpTool.get("https://poloniex.com/public?command=" + command + "&currencyPair=" +currencyPair);
				} catch (HttpConnectionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	            //return json.loads(ret.read())
		 }
		 else if(command.equals("returnMarketTradeHistory"))
			try {
				String currencyPair= (String) req.get("currencyPair");
				ret =  HttpTool.get("https://poloniex.com/public?command=" + "returnTradeHistory" + "&currencyPair=" + currencyPair);
			} catch (HttpConnectionException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		else{
	            //req['command'] = command
	            //req['nonce'] = int(time.time()*1000) 
	    	 	LocalDate today = LocalDate.now();
	    	 	String nonce = ""+System.currentTimeMillis();
	            String post_data = command+"="+nonce;
	            String sign = HMACSHA1.hmacSHA512(API_SECRET, post_data);
	 
	      
//	            headers = {
//	                'Sign': sign,
//	                'Key': self.APIKey
//	            }
	            
	           
	            JSONObject jObject=new JSONObject();
	            
	            jObject.put("command", nonce);
	            
	            
	            try {
					ret = httpTool.jsonPost("https://poloniex.com/tradingApi?"+"Sign="+sign+
							"&Key="+API_KEY, jObject.toString());
				} catch (HttpConnectionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	            
	            Logger logger = Logger.getLogger("MyLogger");
				logger.debug(ret);
	 
	            //ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers))
	            //jsonRet = json.loads(ret.read())
	            //return self.post_process(jsonRet)
	     }
		 
		 return "";
	 }
	 
	 public String returnTicker(){
		 return api_query("returnTicker", null);
	 }
	 
	 public String return24Volume(){
		 return api_query("return24Volume", null);
	 }
	 
	 public String returnOrderBook(String currencyPair){
		 Map paras = new HashMap();
		 paras.put("currencyPair", currencyPair);
		 return api_query("returnOrderBook", paras);
	 }
	 
	 public String returnMarketTradeHistory(String currencyPair){
		 Map paras = new HashMap();
		 paras.put("currencyPair", currencyPair);
		 return api_query("returnMarketTradeHistory", paras);
	 }
	
	 public String returnBalances(){
		 return api_query("returnBalances", null);
	 }
	 
	 // Returns your open orders for a given market, specified by the "currencyPair" POST parameter, e.g. "BTC_XCP"
	    // Inputs:
	    // currencyPair  The currency pair e.g. "BTC_XCP"
	    // Outputs:
	    // orderNumber   The order number
	    // type          sell or buy
	    // rate          Price the order is selling or buying at
	    // Amount        Quantity of order
	    // total         Total value of order (price * quantity)
	
	 public String returnOpenOrders(String currencyPair){
		 Map paras = new HashMap();
		 paras.put("currencyPair", currencyPair);
		 return api_query("returnOpenOrders", paras);
	 }
	 // Returns your trade history for a given market, specified by the "currencyPair" POST parameter
	    // Inputs:
	    // currencyPair  The currency pair e.g. "BTC_XCP"
	    // Outputs:
	    // date          Date in the form: "2014-02-19 03:44:59"
	    // rate          Price the order is selling or buying at
	    // amount        Quantity of order
	    // total         Total value of order (price * quantity)
	    // type          sell or buy
	 public String returnTradeHistory(String currencyPair){
		 Map paras = new HashMap();
		 paras.put("currencyPair", currencyPair);
		 return api_query("returnTradeHistory", paras);
	 }
	 // Places a buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number.
    // Inputs:
    // currencyPair  The curreny pair
    // rate          price the order is buying at
    // amount        Amount of coins to buy
    // Outputs:
    // orderNumber   The order number
	 public String buy(String currencyPair,float rate, float amount){
		 
		 Map paras = new HashMap();
		 paras.put("currencyPair", currencyPair);
		 paras.put("rate", rate);
		 paras.put("amount", amount);
		 return api_query("buy", paras);
		 
	 }
	 // Places a sell order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number.
    // Inputs:
    // currencyPair  The curreny pair
    // rate          price the order is selling at
    // amount        Amount of coins to sell
    // Outputs:
    // orderNumber   The order number
	 public String sell(String currencyPair,float rate, float amount){
		 
		 Map paras = new HashMap();
		 paras.put("currencyPair", currencyPair);
		 paras.put("rate", rate);
		 paras.put("amount", amount);
		 return api_query("sell", paras);
		 
	 }
	 //Cancels an order you have placed in a given market. Required POST parameters are "currencyPair" and "orderNumber".
	 // Inputs:
	 //currencyPair  The curreny pair
	 //orderNumber   The order number to cancel
	 // Outputs:
	  //succes        1 or 0
	 public String  cancel(String currencyPair, String orderNumber){
		 Map paras = new HashMap();
		 paras.put("currencyPair", currencyPair);
		 paras.put("orderNumber", orderNumber);
	
		 return api_query("sell", paras);
	 }
	 // Immediately places a withdrawal for a given currency, with no email confirmation. In order to use this method, the withdrawal privilege must be enabled for your API key. Required POST parameters are "currency", "amount", and "address". Sample output: {"response":"Withdrew 2398 NXT."}
	// Inputs:
	//currency      The currency to withdraw
	// amount        The amount of this coin to withdraw
	// address       The withdrawal address
	// Outputs:
	// response      Text containing message about the withdrawal
	 public String  withdraw(String currency, float amount, String address){
		 Map paras = new HashMap();
		 paras.put("currency", currency);
		 paras.put("amount", amount);
		 paras.put("address", address);
		 return api_query("sell", paras);
	 }


}
